//
//  ConstructReportController.m
//  Runone
//
//  Created by runone02 on 16/11/7.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "ConstructReportController.h"
#import "UITextField+ToolBar.h"
#import "DateViewController.h"
#import "ChooseLineTableViewController.h"
#import "CommonUtilityjudge.h"
#import "RequestHelper.h"
#import "MJExtension.h"
#import "ParModel.h"
#import "SVProgressHUD.h"
#import "BCNetAPIClient.h"
#import "ConstructionEventDetailInfo.h"
#import "TableOperation.h"
#import "PileInfo.h"
#import "EventDealList.h"
#import "CityDirectionController.h"
#import "PromptUtil.h"
#import "LittleVideoViewController.h"
#import "ROActionSheet.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "SGImagePickerController.h"
#import "RampViewController.h"
#import "RODateHelper.h"
#import "NSDate+ROCaculateTime.h"
#import "ROImagePickViewController.h"
#import "AJPhotoPickerViewController.h"
#import "AJPhotoBrowserViewController.h"
#import "HighwayMergeRoadRecordModel.h"
#import "AppDelegate.h"
#import "HighWayRoadRecordDirectionInfoModel.h"
#import "StationListPopViewController.h"

@interface ConstructReportController ()<UIPopoverPresentationControllerDelegate,UITextViewDelegate,UIAlertViewDelegate,UITextFieldDelegate, LittleVideoDelegate,AJPhotoPickerProtocol,AJPhotoBrowserDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    
    AVPlayer *_player;
    AVPlayerItem *_playItem;
    AVPlayerLayer *_playerLayer;
    AVPlayerLayer *_fullPlayer;
    BOOL _isPlaying;
}

@property (weak, nonatomic) IBOutlet UIScrollView *BackScrollView; //底部滚动view
@property (weak, nonatomic) IBOutlet UIView *ContainerView;   //容器view
@property (weak, nonatomic) IBOutlet UIButton *ConfirmBtn;  //提交按钮
@property (weak, nonatomic) IBOutlet UIButton *CancleBtn;   //取消按钮
@property (weak, nonatomic) IBOutlet UITextField *UnitsTF; //施工单位
@property (weak, nonatomic) IBOutlet UITextField *HeaderTF;//现场负责人
@property (weak, nonatomic) IBOutlet UITextField *ContactNO;//联系电话
@property (weak, nonatomic) IBOutlet UITextField *BeginTimeTF;//计划开始时间
@property (weak, nonatomic) IBOutlet UITextField *EndTimeTF;  //计划结束时间
@property (weak, nonatomic) IBOutlet UITextField *BeginPileNO;//开始桩号
@property (weak, nonatomic) IBOutlet UITextField *BeginPileDistance;//开始桩号距离
@property (weak, nonatomic) IBOutlet UITextField *EndPileNO;   //结束桩号
@property (weak, nonatomic) IBOutlet UITextField *EndPileDistance;//结束桩号距离
@property (weak, nonatomic) IBOutlet UITextField *ConstructLocation;//施工地点
@property (weak, nonatomic) IBOutlet UITextField *Direction;        //行车方向
@property (weak, nonatomic) IBOutlet UITextView *ProjectTV;         //施工项目
@property (weak, nonatomic) IBOutlet UITextView *ProjectDealTV;     //施工处置
@property (weak, nonatomic) IBOutlet UIView     *ProjectV; //施工项目的view
@property (weak, nonatomic) IBOutlet UIView     *DisposalV; //施工处置view
@property (nonatomic,strong) UIAlertView *resultAlert;
@property (weak, nonatomic) IBOutlet UITextField *RampOrNo;
@property (weak, nonatomic) IBOutlet UIScrollView *imageScrollView;//图片滚动的view
@property (weak, nonatomic) IBOutlet UIView *VideoV;               //小视频的view
@property (nonatomic, strong) StationListPopViewController *station;

// ********************************************* - - *********************************************

@property(nonatomic,strong)DateViewController *dateVC;//时间VC
@property(nonatomic,strong)CityDirectionController *citypop; //方向
@property(nonatomic,strong)ChooseLineTableViewController *chooseLineVC; //施工地点的路线
@property(nonatomic,strong)RampViewController *rampVC;//匝道
@property(nonatomic,strong)PromptUtil *Prompt;

//
@property(nonatomic, strong) LittleVideoViewController *littleVideoVC;//拍摄小视频界面
@property (nonatomic, strong)  ROActionSheet *sheet;

@property(nonatomic,strong)EventDealList *listModel;

@property(nonatomic)NSInteger code;
@property(nonatomic,strong)NSMutableArray *loadImageArr;

@property(nonatomic)int beginPirNo;
@property(nonatomic)int endPirNo;
@property(nonatomic)int beginPirDistance;
@property(nonatomic)int endPirDistance;
@property(nonatomic,strong)UIImage *img;
@property(nonatomic,strong)UIImageView *iv;

@property (nonatomic) BOOL isHaveVideo;
@property (nonatomic,strong) NSURL *videoUrl;
@property(nonatomic,strong)NSMutableArray   *imageArray;
@property (nonatomic, strong) NSMutableArray *originalImgArr;

@property (strong, nonatomic) NSMutableArray *photos;

@property (nonatomic, strong)NSString *currentUID;//当前道路UID或者是收费站的UID

@property (nonatomic, copy)NSString *directionStr;//方向的数值（1, 2, 3）

@property (nonatomic, strong) HighwayMergeRoadRecordModel *currentHighModel;//当前的线路（主线、南、北）

@property (nonatomic, assign) CGFloat la;
@property (nonatomic, assign) CGFloat lo;
@end

@implementation ConstructReportController

-(void)viewWillAppear:(BOOL)animated {
    [self.tabBarController.tabBar setHidden:YES];
}
- (BOOL)popoverPresentationControllerShouldDismissPopover:(UIPopoverPresentationController *)popoverPresentationController {
    return  YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.BackScrollView.bounces               = NO;
    self.photos = [[NSMutableArray alloc] init];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    label.text     = @"施工事件上报";
    label.textAlignment=NSTextAlignmentCenter;
    label.textColor=[UIColor whiteColor];
    self.navigationItem.titleView=label;
    [self datePick];
    
    [self getDefaultLine]; //获取默认的线路（主线）
    [self TFConfirem];
    [self getDefaultDeirectionArray];
   
    _RampOrNo.text        = @"主 线";

    _BeginTimeTF.delegate = self;
    _EndTimeTF.delegate   = self;
    _Prompt    =     [[PromptUtil alloc] init];
    
    _listModel = [[EventDealList alloc] init];
    
    _ProjectDealTV.delegate     = self;
    _Direction.delegate         = self;
    _ConstructLocation.delegate = self;
    
    _ProjectTV.layer.borderColor   = [UIColor colorWithRed:236.0/255 green:236.0/255 blue:236.0/255 alpha:1].CGColor;
    _ProjectTV.layer.cornerRadius  = 2;
    _ProjectTV.layer.masksToBounds = YES;
    _ProjectTV.layer.borderWidth   = 1;
    
    _ProjectDealTV.layer.borderColor   = [UIColor colorWithRed:236.0/255 green:236.0/255 blue:236.0/255 alpha:1].CGColor;
    _ProjectDealTV.layer.cornerRadius  = 2;
    _ProjectDealTV.layer.masksToBounds = YES;
    _ProjectDealTV.layer.borderWidth   = 1;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"提 交" style:UIBarButtonItemStylePlain target:self action:@selector(Report)];
}

- (void) getDefaultLine {
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    _currentHighModel       = myDelegate.HighWayRoadArray[0];
    _ConstructLocation.text = _currentHighModel.RoadName;
    _currentUID             = _currentHighModel.RoadUID;
}

- (void) getDefaultDeirectionArray {
    NSMutableArray *directionArray = [[NSMutableArray alloc] init];
    for (HighWayRoadRecordDirectionInfoModel *directionModel in _currentHighModel.highWayRoadDirectionList) {
        [directionArray addObject:directionModel.DirectionDescription];//行车方向描述
    }
    _Direction.text = directionArray[0];
    _directionStr = [NSString stringWithFormat:@"%d",1];
}

- (IBAction)CommitBtn:(id)sender {
    [self configCameraBtn];
}

-(void)configCameraBtn {
    [self cameraBtnClick];
}

- (void) cameraBtnClick {
//    NSLog(@"这个照相机哦");
    LittleVideoViewController *vc = [[LittleVideoViewController alloc] init];
    vc.delegate = self;
    [self.navigationController presentViewController:vc animated:YES completion:nil];
}

- (void) UpLoadPictures {
    if (self.originalImgArr.count >= 5) {
        [SVProgressHUD showErrorWithStatus:@"不能选择超过5张图"];
        return;
    }
    AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
    picker.maximumNumberOfSelection = 5 - _originalImgArr.count;
    picker.multipleSelection        = YES;
    picker.assetsFilter             = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups          = YES;
    picker.delegate                 = self;
    picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return YES;
    }];
    [self presentViewController:picker animated:YES completion:nil];
}

-(void)TFConfirem {
    [_UnitsTF setTextFieldInputAccessoryView:_UnitsTF frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    _UnitsTF.clearButtonMode=UITextFieldViewModeAlways;
    
    [_HeaderTF setTextFieldInputAccessoryView:_HeaderTF frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    _HeaderTF.clearButtonMode=UITextFieldViewModeAlways;
    
    [_ContactNO setTextFieldInputAccessoryView:_ContactNO frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    _ContactNO.clearButtonMode=UITextFieldViewModeAlways;
    [self configLabel];
    [_BeginPileNO setTextFieldInputAccessoryView:_BeginPileNO frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    
    [_BeginPileDistance setTextFieldInputAccessoryView:_BeginPileDistance frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];

    [_EndPileNO setTextFieldInputAccessoryView:_EndPileNO frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    [_EndPileDistance setTextFieldInputAccessoryView:_EndPileDistance frame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    
}

- (void)configLabel {

        if ([_currentHighModel.RoadUID isEqualToString:@"8dd13d88-cb02-4471-876b-1dfe39419ee6"]) {
            UILabel *label1 = [[UILabel alloc] init];
            label1.text = @"K";
            label1.frame = CGRectMake(0, 5, 10, 40);
            _BeginPileNO.leftView = label1;
            _BeginPileNO.leftViewMode = UITextFieldViewModeAlways;
            
            UILabel *label2 = [[UILabel alloc] init];
            label2.text = @"K";
            label2.frame = CGRectMake(0, 5, 10, 40);
            _EndPileNO.leftView = label2;
            _EndPileNO.leftViewMode = UITextFieldViewModeAlways;
            
        }else {
            UILabel *label1 = [[UILabel alloc] init];
            label1.text = @"LK";
            label1.font          = [UIFont boldSystemFontOfSize:15];
            label1.frame =  CGRectMake(0, 0, 25, 10);
            _BeginPileNO.leftView = label1;
            _BeginPileNO.leftViewMode = UITextFieldViewModeAlways;
            
            UILabel *label2 = [[UILabel alloc] init];
            label2.text = @"LK";
            label2.font  = [UIFont boldSystemFontOfSize:15];
            label2.frame =  CGRectMake(0, 0, 25, 10);
            _EndPileNO.leftView = label2;
            _EndPileNO.leftViewMode = UITextFieldViewModeAlways;
        }
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return NO;
}

- (IBAction)popCityDir:(UIButton *)btn {
    _citypop   = [[CityDirectionController alloc] init];
    _citypop.currentModel  = _currentHighModel;
    _citypop.modalPresentationStyle=UIModalPresentationPopover;
    __weak typeof(self) weakSelf=self;
    _citypop.LineBlock=^(NSString *str, NSInteger index){
        weakSelf.Direction.text = str;
        _directionStr = [NSString stringWithFormat:@"%d",(int)index];
        
    };
    _citypop.popoverPresentationController.sourceView=btn;
    _citypop.popoverPresentationController.delegate=self;
    _citypop.popoverPresentationController.sourceRect=CGRectMake(135, 109, 0, 0);
    _citypop.popoverPresentationController.permittedArrowDirections=NO;
    [self presentViewController:_citypop animated:YES completion:nil];
}

- (IBAction)RampBtn:(UIButton *)sender {
    __weak typeof(self) weakSelf = self;
    AppDelegate *myDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
    if ([_ConstructLocation.text isEqualToString: @"收费站"]) {
        _station                          = [[StationListPopViewController alloc] init];
        _station.modalPresentationStyle   = UIModalPresentationPopover;
        _station.popoverPresentationController.sourceView = sender;
        _station.popoverPresentationController.delegate   = self;
        _station.popoverPresentationController.sourceRect = CGRectMake(80, 135, 0,0);
        _station.popoverPresentationController.permittedArrowDirections = NO;
        _station.LineBlock=^(StationModel *model){
            weakSelf.RampOrNo.text = model.TollStationName;
            _la = model.Latitude;
            _lo = model.Longitude;
            _currentUID = model.TollStationUID;
            for (HighwayMergeRoadRecordModel *highModel in myDelegate.HighWayRoadArray) {
                if ([highModel.RoadUID isEqualToString:model.RoadUID]) {
                    _currentHighModel = highModel;
                    [weakSelf configLabel];
                }
            }
            [weakSelf getDefaultDeirectionArray];
            NSInteger length = model.PileNo.length;
            weakSelf.BeginPileNO.text       = [model.PileNo substringWithRange:NSMakeRange(1,  length -1)];
            weakSelf.BeginPileDistance.text = [NSString stringWithFormat:@"%ld",(long)model.PileDistance];
            weakSelf.EndPileNO.text         = [model.PileNo substringWithRange:NSMakeRange(1,  length -1)];
            weakSelf.EndPileDistance.text   = [NSString stringWithFormat:@"%ld",(long)model.PileDistance];
             weakSelf.BeginPileNO.enabled          = NO;
             weakSelf.BeginPileDistance.enabled    = NO;
             weakSelf.EndTimeTF.enabled            = NO;
             weakSelf.EndPileDistance.enabled      = NO;
        };
        [self presentViewController:_station animated:YES completion:nil];
    }else {
        _rampVC=[[RampViewController alloc] init];
        _rampVC.modalPresentationStyle=UIModalPresentationPopover;
        _rampVC.RampBlock=^(NSInteger index){
            if (index==0) {
                weakSelf.RampOrNo.text=@"主 线";
            }
            if (index==1) {
                weakSelf.RampOrNo.text=@"匝 道";
            }
        };
        _rampVC.popoverPresentationController.sourceView=sender;
        _rampVC.popoverPresentationController.delegate=self;
        _rampVC.popoverPresentationController.sourceRect=CGRectMake(80, 85, 0, 0);
        _rampVC.popoverPresentationController.permittedArrowDirections=NO;
        [self presentViewController:_rampVC animated:YES completion:nil];
    }
}


-(void)datePick {
    _dateVC=[[DateViewController alloc] init];
    _dateVC.modalPresentationStyle=UIModalPresentationPopover;
    _dateVC.popoverPresentationController.sourceView=self.view;
    _dateVC.popoverPresentationController.sourceRect=CGRectMake(self.view.center.x-56, self.view.center.y, 0, 0);
    _dateVC.popoverPresentationController.permittedArrowDirections=NO;
    _dateVC.popoverPresentationController.delegate=self;
}

-(void)textViewDidBeginEditing:(UITextView *)textView {
    if ([_ProjectDealTV.text isEqualToString:@"请输入事件描述："]) {
        _ProjectDealTV.text=@"";
        _ProjectDealTV.textColor = [UIColor blackColor];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.text.length<1) {
        textView.text = @"请输入事件描述：";
        textView.textColor = [UIColor grayColor];
    }
}

-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone;
}

- (IBAction)drop:(UIButton *)btn {
    _chooseLineVC = [[ChooseLineTableViewController alloc] init];
    _chooseLineVC.modalPresentationStyle                                 = UIModalPresentationPopover;
    _chooseLineVC.popoverPresentationController.sourceView               = btn;
    _chooseLineVC.popoverPresentationController.delegate                 = self;
    _chooseLineVC.popoverPresentationController.sourceRect               = CGRectMake(70,109,0, 0);
    _chooseLineVC.popoverPresentationController.permittedArrowDirections = NO;
    [self presentViewController:_chooseLineVC animated:YES completion:nil];
    __weak typeof(self) weakSelf=self;
    _chooseLineVC.LineBlock = ^(NSString *lineStr, NSString *uidStr, NSInteger indexRow){
        weakSelf.ConstructLocation.text = lineStr;
        if (![uidStr isEqualToString:@""]) {
            _currentUID = uidStr;
            AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            _currentHighModel = myDelegate.HighWayRoadArray[indexRow]; //获取当前道路的模型
            weakSelf.BeginPileNO.text = nil;
            weakSelf.EndPileNO.text   = nil;
            weakSelf.BeginPileDistance.text = nil;
            weakSelf.EndPileDistance.text   = nil;
            [weakSelf getDefaultDeirectionArray];
            [weakSelf configRampOrNo];
            weakSelf.BeginPileNO.enabled = YES;
            weakSelf.BeginPileDistance.enabled = YES;
            weakSelf.EndPileNO.enabled = YES;
            weakSelf.EndPileDistance.enabled = YES;
            [weakSelf configLabel];

        }else  {
            _currentUID = nil;
            weakSelf.BeginPileNO.text = nil;
            weakSelf.EndPileNO.text   = nil;
            weakSelf.BeginPileDistance.text = nil;
            weakSelf.EndPileDistance.text   = nil;
            [weakSelf configStation];
            [weakSelf configLabel];
        }
    };
}

- (void) configStation {
    AppDelegate *myDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
    StationModel *model = myDelegate.AllTollStationArray[0];
    _currentUID = model.TollStationUID;
    _la         = model.Latitude;
    _lo         = model.Longitude;
    for (HighwayMergeRoadRecordModel *highModel in myDelegate.HighWayRoadArray) {
        if ([highModel.RoadUID isEqualToString:model.RoadUID]) {
            _currentHighModel = highModel;
        }
    }
    [self configLabel];
    [self getDefaultDeirectionArray];
  
    self.RampOrNo.text          = model.TollStationName;
    self.BeginPileNO.text       = [model.PileNo substringWithRange:NSMakeRange(1, 1)];
    self.BeginPileDistance.text = [NSString stringWithFormat:@"%ld",(long)model.PileDistance];
    self.EndPileNO.text         = [model.PileNo substringWithRange:NSMakeRange(1, 1)];
    self.EndPileDistance.text   = [NSString stringWithFormat:@"%ld",(long)model.PileDistance];
    self.BeginPileNO.enabled       = NO;
    self.BeginPileDistance.enabled = NO;
    self.EndPileNO.enabled         = NO;
    self.EndPileDistance.enabled   = NO;
}

- (void) configRampOrNo {
self.RampOrNo.text = @"主线";
}

#pragma mark - 开始时间选择器
- (IBAction)planBeginTimeMethod:(UIButton *)sender {
    __weak typeof(self) weakSelf=self;
    [self datePick];
    _dateVC.dateBlock=^(NSString *str){
        weakSelf.BeginTimeTF.text=str;
    };
    
    [self presentViewController:_dateVC animated:YES completion:nil];
}

- (IBAction)planEndTimeMethod:(UIButton *)sender {
    __weak typeof(self) weakSelf=self;
    [self datePick];
    _dateVC.dateBlock=^(NSString *str){
        weakSelf.EndTimeTF.text=str;
    };
    
    [self presentViewController:_dateVC animated:YES completion:nil];
}

-(void)requestC {
    RequestGinsengModel *getCurrentEventModel=[[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL=GetEventDataURL;
    getCurrentEventModel.DataValue = [self dataValueJson];
    getCurrentEventModel.UpdatedTime=@"2012-01-12 12:00:00";
    getCurrentEventModel.SystemCode=@"GuangleHighway";
    getCurrentEventModel.MethodName=@"ReportConstructionEventDetailInfo";
    [self requestTestUpdateImage:getCurrentEventModel Image:_originalImgArr];
}

-(void)requestTestUpdateImage:(RequestGinsengModel *)RequestGinseng Image:(NSArray *)LoadImages {
    
    [SVProgressHUD showWithStatus:@"正在上传,请稍后......"];
    
    NSDictionary *dic=[[NSDictionary alloc] init];
    dic = @{@"methodName":RequestGinseng.MethodName,@"updatedtime":RequestGinseng.UpdatedTime,@"systemcode":DefaultSystemCode,@"DataValue":RequestGinseng.DataValue};
    NSMutableArray *images = [[NSMutableArray alloc] init];
    [images addObjectsFromArray:LoadImages];
    
    [BCNetAPIClient PostVideosAndImages:GetEventDataURL parameters:dic imageArray:images videoArray:_videoUrl.absoluteString success:^(id responseObjecet) {
        [SVProgressHUD showSuccessWithStatus:@"上报成功"];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        [SVProgressHUD showSuccessWithStatus:@"上报失败"];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}
- (IBAction)ChooseImage:(UIButton *)sender {
    [self UpLoadPictures];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex==0) {
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(NSString *)dataValueJson {
    ConstructionEventDetailInfo *info=[[ConstructionEventDetailInfo alloc] init];
    info.Content=self.ProjectTV.text;
    info.EventBaseInfo=[[EventBaseInfo alloc] init];
    
//    NSArray *arr=[[TableOperation shareInstance]  getePirNoTableOfRow:[@"K" stringByAppendingString:self.BeginPileNO.text]];
//    for (PileInfo *pir in arr) {
////        NSLog(@"%f,%f",pir.Latitude,pir.Longitude);
//        info.EventBaseInfo.Latitude=pir.Latitude;
//        info.EventBaseInfo.Longitude=pir.Longitude;
//    }
//    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    
    info.Department = self.UnitsTF.text;
    info.Header=self.HeaderTF.text;
    info.Telephone=_ContactNO.text;
    
    NSString *k=@"K";
    info.EventBaseInfo.BeginPile=[k stringByAppendingString:self.BeginPileNO.text];
    info.EventBaseInfo.BeginPileDistance=[self.BeginPileDistance.text integerValue];
    info.EventBaseInfo.EndPile=[k stringByAppendingString:self.EndPileNO.text];
    info.EventBaseInfo.EndPileDistance=[self.EndPileDistance.text integerValue];
    info.EventBaseInfo.IncidentSource=@"2";
    
    if ([_ConstructLocation.text isEqualToString:@"收费站"]) {
        info.EventBaseInfo.TollStationUID   = _currentUID;
        info.EventBaseInfo.TollStationName  = _RampOrNo.text;
        info.EventBaseInfo.RoadUID          = _currentHighModel.RoadUID;
        info.EventBaseInfo.RoadDerection    = _directionStr;
        info.EventBaseInfo.RoadDerectionName= _Direction.text;
        info.EventBaseInfo.Latitude         = _la;
        info.EventBaseInfo.Longitude        = _lo;
//        NSLog(@"%@ %@ %@ %@",_RampOrNo.text, _Direction.text, _currentUID, _currentHighModel.RoadUID);
    }else {
        info.EventBaseInfo.RoadUID           = _currentUID;
        info.EventBaseInfo.RoadDerection     = _directionStr;
        info.EventBaseInfo.RoadDerectionName = _Direction.text;
        
        AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        for (PileInfo *modelPile in myDelegate.PirArray) {
            if ([modelPile.RoadUID isEqualToString:info.EventBaseInfo.BeginPile] && [info.EventBaseInfo.BeginPile isEqualToString:modelPile.PileNo] ) {
                info.EventBaseInfo.Latitude  = modelPile.Latitude;
                info.EventBaseInfo.Longitude = modelPile.Longitude;
            }
        }
    }

    info.EventBaseInfo.OccurTime          = self.BeginTimeTF.text;
    info.EventBaseInfo.EndTime            = self.EndTimeTF.text;
    info.EventBaseInfo.IncidentSource     = [NSString stringWithFormat:@"%d",2];
    info.EventBaseInfo.IncidentType       = @"3";
    info.EventBaseInfo.IncidentParentType = @"3 ";
    info.EventBaseInfo.IncidentDetail     = self.ProjectDealTV.text;
    info.EventBaseInfo.DealDetail         = self.ProjectDealTV.text;
    _listModel.DealDetail                 = self.ProjectDealTV.text;
    
    info.EventDealList =@[_listModel];
    
    NSMutableDictionary *dic=info.mj_keyValues;
    NSString *json = [dic mj_JSONString];
    NSLog(@"%@",json);
    
    ParModel *model=[[ParModel alloc] init];
    model.key=@"ConstructionEventDetailInfo";
    model.value=json;
    
    NSMutableDictionary *ModelDic=model.mj_keyValues;
    NSString *dataValue = [ModelDic mj_JSONString];
    NSString *str=@"[";
    NSString *temp=[str stringByAppendingString:dataValue];
    NSString *str1=@"]";
    NSString *JsonString=[temp stringByAppendingString:str1];
    
    return JsonString;
}
- (void)Report {
    
    if (stringIsEmpty(_UnitsTF.text)) {
        [_Prompt alert:@"施工单位不能为空"];
        return;
    }
    
    
    if (_UnitsTF.text.length > 50) {
        [_Prompt alert:@"施工单位长度不能大于20个字"];
        return;
    }
    
    if (stringIsEmpty(_HeaderTF.text)) {
        [_Prompt alert:@"现场负责人不能为空"];
        return;
    }
    
    if (_HeaderTF.text.length > 5) {
        [_Prompt alert:@"现场负责人不能超过5个字"];
        return;
    }
    
    if (stringIsEmpty(_ContactNO.text)) {
        [_Prompt alert:@"联系电话不能为空"];
        return;
    }
    if (_ContactNO.text.length > 11) {
        [_Prompt alert:@"请输入正确的联系电话"];
        return;
    }
    if (stringIsEmpty(_BeginPileNO.text)) {
        [_Prompt alert:@"开始桩号不能为空"];
        return;
    }
    if ([_ConstructLocation.text isEqualToString:@"主线"]&&[_BeginPileNO.text intValue]>269) {
        [_Prompt alert:@"主线开始桩号不能大于269"];
        return;
    }
    if ([_ConstructLocation.text isEqualToString:@"韶赣北连线"]&&[_BeginPileNO.text intValue]>32) {
        [_Prompt alert:@"韶赣北连线开始桩号不能大于32"];
        return;
    }
    if ([_ConstructLocation.text isEqualToString:@"韶赣南连线"]&&[_BeginPileNO.text intValue]>3) {
        [_Prompt alert:@"韶赣南连线开始桩号不能大于3"];
        return;
    }
    if (stringIsEmpty(_BeginPileDistance.text)) {
        [_Prompt alert:@"开始桩距离不能为空"];
        return;
    }
    if ([_BeginPileDistance.text intValue]>999) {
        [_Prompt alert:@"桩距离不能大于999"];
        return;
    }
    if (stringIsEmpty(_EndPileNO.text)) {
        [_Prompt alert:@"结束桩号不能为空"];
        return;
    }
    if ([_ConstructLocation.text isEqualToString:@"主线"]&&[_EndPileNO.text intValue]>269) {
        [_Prompt alert:@"主线结束桩号不能大于269"];
        return;
    }
    if ([_ConstructLocation.text isEqualToString:@"韶赣北连线"]&&[_EndPileNO.text intValue]>32) {
        [_Prompt alert:@"韶赣北连线结束桩号不能大于32"];
        return;
    }
    if ([_ConstructLocation.text isEqualToString:@"韶赣南连线"]&&[_EndPileNO.text intValue]>3) {
        [_Prompt alert:@"韶赣南连线结束桩号不能大于3"];
        return;
    }
    if (stringIsEmpty(_EndPileDistance.text)) {
        [_Prompt alert:@"结束桩距离不能为空"];
        return;
    }
    if ([_EndPileDistance.text intValue]>999) {
        [_Prompt alert:@"桩距离不能大于999"];
        return;
    }
    if (stringIsEmpty(_Direction.text)) {
        [_Prompt alert:@"请选择线路"];
        return;
    }
    if (stringIsEmpty(_BeginTimeTF.text)) {
        [_Prompt alert:@"请选择开始时间"];
        return;
    }
    if (stringIsEmpty(_EndTimeTF.text)) {
        [_Prompt alert:@"请选择结束时间"];
        return;
    }
    NSDate *beginDate = [RODateHelper dateFromString:_BeginTimeTF.text withFormat:nil];
    NSInteger beginInter = [beginDate compareToCurrentDate];
    NSDate *endDate = [RODateHelper dateFromString:_EndTimeTF.text withFormat:nil];
    if (beginInter != 1) {
        [_Prompt alert:@"开始时间不能小于当前时间"];
        return;
    }
    
    NSInteger twoDateCompare = [endDate compareToToDate:beginDate];
    if (twoDateCompare != 1 ) {
        [_Prompt alert:@"结束时间不能小于开始时间"];
        return;
    }
    
    if (stringIsEmpty(_ProjectTV.text)) {
        [_Prompt alert:@"施工项目不能为空"];
        return;
    }
    if (stringIsEmpty(_ProjectDealTV.text)) {
        [_Prompt alert:@"施工处理不能为空"];
        return;
    }
    
    if (_ProjectDealTV.text.length > 1000) {
        [_Prompt alert:@"施工处理不能超过1000字"];
        return;
    }
    
    if ([_ProjectDealTV.text isEqualToString:@"请输入事件描述："])
    {
        [_Prompt alert:@"请输入事件描述"];
        return;
    }
    if ([self isNumber:_BeginPileNO.text]) {
        [_Prompt alert:@"请输入整形数字开始桩号"];
        return;
    }
    else
    {
        _beginPirNo=[_BeginPileNO.text intValue];
    }
    if ([self isNumber:_EndPileNO.text]) {
        [_Prompt alert:@"请输入整形数字结束桩号"];
        return;
    }
    else
    {
        _endPirNo=[_EndPileNO.text intValue];
        
    }
    if ([self isNumber:_BeginPileDistance.text]) {
        [_Prompt alert:@"请输入整形数字开始桩距离"];
        return;
    }
    else
    {
        _beginPirDistance=[_BeginPileDistance.text intValue];
        
    }
    if ([self isNumber:_EndPileDistance.text]) {
        [_Prompt alert:@"请输入整形数字结束桩距离"];
        return;
    }
    else
    {
        _endPirDistance=[_EndPileDistance.text intValue];
        
    }
    if (_beginPirNo>_endPirNo) {
        [_Prompt alert:@"起始桩号不能大于结束桩号"];
        return;
    }
    if (_beginPirNo==_endPirNo) {
        if (_beginPirDistance>_endPirDistance) {
            [_Prompt alert:@"开始装桩距离不能大于结束桩距离"];
            return;
        }
    }
    if (_beginPirDistance>=999) {
        [_Prompt alert:@"开始桩距离不能大于999"];
        return;
    }
    if (_endPirDistance>=999) {
        [_Prompt alert:@"结束桩距离不能大于999"];
        return;
    }
    if (!validatePhone(_ContactNO.text)) {
        [_Prompt alert:@"请输入有效的电话号码"];
        return;
    }
    
    [self requestC];
    
}

- (BOOL) isNumber:(NSString *)text;
{
    NSString *regex =@"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if (![pred evaluateWithObject:text]) {
        NSLog(@"不是");
        return YES;
    }
    NSLog(@"是");
    return NO;
}
//提示
-(void)resultMessage:(NSString *)result {
    _resultAlert=[[UIAlertView alloc] initWithTitle:@"提示" message:result delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [_resultAlert show];
}

#pragma mark - BoPhotoPickerProtocol
- (void)photoPickerDidCancel:(AJPhotoPickerViewController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoPicker:(AJPhotoPickerViewController *)picker didSelectAssets:(NSArray *)assets {
    [self.photos addObjectsFromArray:assets];
    [picker dismissViewControllerAnimated:NO completion:nil];
    
    
    if (_originalImgArr.count > 0) {
        [_originalImgArr removeAllObjects];
    }
    _originalImgArr = [[NSMutableArray alloc] init];
    for (int i = 0 ; i < self.photos.count; i++) {
        ALAsset *asset = self.photos[i];
        UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        [_originalImgArr addObject:tempImg];
    }
    [self configImages];
}

- (void) configImages {
    CGFloat x = 0;
    CGRect frame = CGRectMake(0, 0, 125, 125);
    self.imageScrollView.hidden = NO;
    for (int i = 0; i < _originalImgArr.count; i ++) {
        frame.origin.x = x;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        [imageView setContentMode:UIViewContentModeScaleAspectFill];
        imageView.clipsToBounds = YES;
        imageView.image = _originalImgArr[i];
        imageView.tag = i;
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBig:)]];
        [self.imageScrollView addSubview:imageView];
        x += frame.size.width+5;
        self.imageScrollView.contentSize = CGSizeMake(125 * _originalImgArr.count + 5 * _originalImgArr.count, 0);
    }
}

- (void) removeDeleteImages {
    for (UIImageView *imageV in _imageScrollView.subviews) {
        [imageV removeFromSuperview];
    }
}

- (void)showBig:(UITapGestureRecognizer *)sender {
    NSInteger index = sender.view.tag;
    AJPhotoBrowserViewController *photoBrowserViewController = [[AJPhotoBrowserViewController alloc] initWithPhotos:self.photos index:index];
    photoBrowserViewController.delegate = self;
    [self presentViewController:photoBrowserViewController animated:YES completion:nil];
}

- (void)photoBrowser:(AJPhotoBrowserViewController *)vc deleteWithIndex:(NSInteger)index {
    [self.originalImgArr removeObjectAtIndex:index];
    [self.photos removeObjectAtIndex:index];
    [self removeDeleteImages];
    [self configImages];
}

- (void)photoBrowser:(AJPhotoBrowserViewController *)vc didDonePhotos:(NSArray *)photos {
    [vc dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoPickerTapCameraAction:(AJPhotoPickerViewController *)picker {
//    [SVProgressHUD showErrorWithStatus:@"该功能有待完善"];
//    [self checkCameraAvailability:^(BOOL auth) {
//        if (!auth) {
//            NSLog(@"没有访问相机权限");
//            return;
//        }
//        [picker dismissViewControllerAnimated:NO completion:nil];
//        UIImagePickerController *cameraUI = [UIImagePickerController new];
//        cameraUI.allowsEditing   = NO;
//        cameraUI.delegate        = self;
//        cameraUI.sourceType      = UIImagePickerControllerSourceTypeCamera;
//        cameraUI.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
//        [self presentViewController: cameraUI animated: YES completion:nil];
//    }];
}
- (void)checkCameraAvailability:(void (^)(BOOL auth))block {
    BOOL status = NO;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusAuthorized) {
        status = YES;
    } else if (authStatus == AVAuthorizationStatusDenied) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusRestricted) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){
                if (block) {
                    block(granted);
                }
            } else {
                if (block) {
                    block(granted);
                }
            }
        }];
        return;
    }
    if (block) {
        block(status);
    }
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage;
    if (CFStringCompare((CFStringRef) mediaType,kUTTypeImage, 0)== kCFCompareEqualTo) {
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(originalImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
    if (!error) {
        NSLog(@"保存到相册成功");
        AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
        picker.maximumNumberOfSelection = 5  - _originalImgArr.count;
        picker.multipleSelection        = YES;
        picker.assetsFilter             = [ALAssetsFilter allPhotos];
        picker.showEmptyGroups          = YES;
        picker.delegate                 = self;
        picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            return YES;
        }];
        [self dismissViewControllerAnimated:NO completion:nil];
        [self presentViewController:picker animated:NO completion:nil];
    }else{
        NSLog(@"保存到相册出错%@", error);
    }
}


// *********** - 播放小视频 - *************
#pragma mark -littleVideoDelegate
- (void)finishLittleVideoViewControllerCapture:(NSURL *)filePath {
    _videoUrl = filePath;
    [self crreatPlayViedeo:filePath];
    
}
- (void) crreatPlayViedeo:(NSURL *)videoUrl {
    _playItem = [AVPlayerItem playerItemWithURL:videoUrl];
    _player = [AVPlayer playerWithPlayerItem:_playItem];
    _playerLayer =[AVPlayerLayer playerLayerWithPlayer:_player];
    _playerLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 16, 200);
    _playerLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;//视频填充模式
    [self.VideoV.layer addSublayer:_playerLayer];
    [_player play];
    _isHaveVideo   = YES;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_player pause];
    _player = nil;
    [_sheet hiddenSheet];
}



@end
